package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.GeoModel;
import models.RouteModel;
import admin.data.GeoData;
import admin.data.RouteData;

public class EditRouteServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap check = new TreeMap();
		GeoData geoData = new GeoData();
		RouteData routeData = new RouteData();
		RouteModel routeModel = new RouteModel();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String params = path.replaceAll("/admin/route/edit/", "");
		if(params.length()>7)
		{
			routeModel = routeData.getRoute(params);
		}
		else
		{
			response.sendRedirect("/admin/route/list/");
		}
		
		ArrayList<GeoModel> geos = geoData.getAll();
		
		request.setAttribute("check", check);
		request.setAttribute("geos", geos);
		request.setAttribute("routeModel", routeModel);
		
		try {
			request.getRequestDispatcher("/admin/pages/edit_route.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap check = new TreeMap();
		RouteData routeData = new RouteData();
		RouteModel routeModel = new RouteModel();
		
		String routeId = (String) request.getParameter("routeId");
		String name = (String) request.getParameter("name");
		String description = (String) request.getParameter("description");
		String geoName = (String) request.getParameter("geoName");
		String geoId = (String) request.getParameter("geoId");
		
		if ((name == null || name.equals(""))) {
			check.put("name", "Bạn chưa nhập tên tuyến.");
		}
		
		if (check.size() == 0) {
			routeModel.setId(routeId);
			routeModel.setName(name);
			routeModel.setListGeoName(geoName);
			routeModel.setListGeoId(geoId);
			routeModel.setDescription(description);
			routeData.insert(routeModel);
			request.setAttribute("success", "Bạn đã thay đổi tuyến thành công.");
			
			routeModel = new RouteModel();
		}		
		response.sendRedirect("/admin/route/edit/"+routeId);
	}
	
}
